package com.lczc.soa.controller;

import com.lczc.soa.domain.News;
import com.lczc.soa.domain.SearchNewsResponse;
import com.lczc.soa.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
@RequestMapping("/News")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @RequestMapping("/list")
    public String PolicyPage(Model model){
        List<News> newss =newsService.listNews();
        model.addAttribute("newss",newss);
        return "news_list";
    }

    @RequestMapping("/newslist")
    public  String NewsadminList(){   return "newsadmin_list";
    }

    @GetMapping("/api/search")
    @ResponseBody
    public SearchNewsResponse searchNewsResponse(@RequestParam("pageNum") Integer pageNum,
                                             @RequestParam("pageSize") Integer pageSize) {
    return newsService.findAllNews(pageNum, pageSize);
}

    @GetMapping("/api/searchLike")
    @ResponseBody
    public SearchNewsResponse searchNewsResponseLike(@RequestParam("keywords") String keywords,
                                                       @RequestParam("pageNum") Integer pageNum,
                                                       @RequestParam("pageSize") Integer pageSize) {
        return newsService.findNewsLikeTopic(keywords, pageNum, pageSize);
    }

    @RequestMapping("/toadd")
    public String addnewsPage(Model model){
        model.addAttribute("news",new News());
        return "news_submit";
    }
    @RequestMapping("/add")
    public String addNews(News news, HttpServletRequest request){
        news.setNewsTopic(request.getAttribute("newsTopic").toString());
        news.setContent(request.getAttribute("content").toString());
        news.setNewsAuthor(request.getAttribute("newsAuthor").toString());
//        System.out.println("Controller:" + area.getAreaName());
        int updated = newsService.saveNews(news);
        return "redirect:/News/newslist";
    }




    @DeleteMapping("/delete")
    @ResponseBody
    public Boolean deleteArea(@RequestParam("id") String id){
        int deleted = newsService.deleteNews(id);
        return deleted > 0;
    }
    @RequestMapping("/content")
    public String PolicyContent(@RequestParam("id") String id,Model model){
        News news = newsService.findNewsByPrimaryKey(id);
        model.addAttribute("news",news);
        return "news_content";
    }






}
